package com.z2f.config;

import com.alibaba.fastjson.JSON;
import com.z2f.entity.ResultSet;
import com.z2f.utils.RedisUtils;
import com.z2f.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;


@Component
public class TokenAuthInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisUtils redisUtils;

    // before 在..之前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        // 1.判断handler 是不是需要拦截的方法
        // instanceof 判断object是否未某个类的实例
        response.setContentType("text/html;charset=utf-8");
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        // 2.获取方法
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        // 3.获取方法的注解
        //  isAnnotationPresent(TokenPass.class) 判断该方法是否有TokenPass的注解
        if (method.isAnnotationPresent(TokenPass.class)) {
            return true;
        }
        // 4.判断该方法是否是否有TokenRequire注解
        if (method.isAnnotationPresent(TokenRequire.class)) {
            // 5.获取请求头中的token
            // 请求头的信息也是键值对的形式
            System.out.println("-----=");

            String token = request.getHeader("token");
            System.out.println(token);
            // 6.验证token是否有效
            if (token == null || token.equals("")) {
                // 应答为
                // return false 拦截器直接拦截 不会到后台
                // 所以拦截器直接用response返回信息给前台
                try {
                    response.getWriter().print(JSON.toJSONString(ResultSet.fail("token为空")));
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return false;
            }
            // 7.验证token是否在有效时间 + 签名(账号+密码)
            else {
                String userId = "";
                userId = TokenUtils.getUserIdFromToken(token);

                if (userId == null) {
                    response.getWriter().print(JSON.toJSONString(ResultSet.fail("token不存在")));
                    return false;
                } else {
                    String redisToken = (String) redisUtils.get(userId);
                    if (token.equals(redisToken)) {
                        long expire = redisUtils.getExpire(userId);
                        if (expire > 0) {
                            if (expire < 300) {
                                redisUtils.expire(userId, 60);
                            }
                            return true;
                        } else {
                            System.out.println("过期啦！");
                            PrintWriter writer = response.getWriter();
                            writer.print(JSON.toJSONString(ResultSet.fail("token过期")));
                            return false;
                        }
                    } else {
                        System.out.println("错误！");
                        PrintWriter writer = response.getWriter();
                        writer.print(JSON.toJSONString(ResultSet.fail("token错误")));
                    }
                    // Boolean aBoolean = TokenUtils.checkToken(token, "账号", "密码");
                    // 8.验证权限
                }
            }
        }
            return false;
        }

        // around 环绕
        @Override
        public void postHandle (HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView
        modelAndView) throws Exception {

        }

        // after 在..之后
        @Override
        public void afterCompletion (HttpServletRequest request, HttpServletResponse response, Object handler, Exception
        ex) throws Exception {

        }
    }
